<?php
class User extends Model{
	protected $table_name = 'shouce_user';
	
	//获取用户id
	public function get_user_id($name0email){
		$user = $this->find(array('email'=>$name0email),'id');
		if(!empty($user)) return $user['id'];
		$user = $this->find(array('name'=>$name0email),'id');
		if(!empty($user)) return $user['id'];
		return false;
	}
	
	public function get_user($uid='',$field='id,name,email'){
		if(empty($uid)) $uid = empty($_SESSION['user']['id']) ? '':$_SESSION['user']['id'];
		$user = $this->find(array('id'=>$uid),$field);
		return $user;
	}
	
	public function get_user_info($uid='',$field='name'){
		if(empty($uid)) $uid = empty($_SESSION['user']['id']) ? '':$_SESSION['user']['id'];
		$user = $this->find(array('id'=>$uid),$field);
		return isset($user[$field])?$user[$field]:'';
	}
	
	//TODO:后期考虑cookie记录相关信息
	public function login($name0email,$password){
		$uid = $this->get_user_id($name0email);
		if($this->find(array('id'=>$uid,'password'=>$password))) {
			$this->set_login_by_id($uid);
			return $uid;
		}
		return false;
	}
	
	//TODO:后期cookie清除
	public function logout(){
		unset($_SESSION['user']);
		setcookie('user',0,0,'/',DOMAIN);
	}
	
	
	public function set_login_by_id($user_id){
		$data= $this->find(array('id'=>$user_id),'id,name,email');
		if(empty($data)) return false;
		$this->set_login_data($data);
	}
	
	public function set_login_data($data){
		$_SESSION['user'] = $data;
		
		//不安全的cookie记录  重要操作不可通过cookie验证
        setcookie('user', "{$data['id']}|{$data['name']}|{$data['email']}", time() + 86400*30, '/', DOMAIN);
	}
	
	//判断是否登录  返回uid 或false
	public function is_login(){
		if(!empty($_SESSION['user']['id'])) {
			return $_SESSION['user']['id'];
		}
		return false;
	}
	
	
	
	//$email先转小写  $password转密文 不用检测重复/空
	public function reg_user($name,$email,$password){
		if(empty($name)||empty($email)||empty($password)) return false;
		if($this->had_name($name) || $this->had_email($email)) return false;
		$time = time();
		return $this->insert(array('name'=>$name,'email'=>$email,'password'=>$password,'cr_time'=>$time));
	}
	
	public function had_name($name) {
		if($this->find(array('name'=>$name))) return true;
		return false;
	}
	public function had_email($email) {
		if($this->find(array('email'=>$email))) return true;
		return false;
	}

	public function encode_password($password) {
		return md5(md5(trim($password)));
	}
	
	//TODO:检测cookie 记session
	public function __construct(){
		if(!session_id()) {
			session_start();
		}
		parent::__construct();
	}
	
	//TODO:cookie  细化权限 发表一定数量后 返回无
	public function has_power(){
		if($this->is_login()) return true;
	}
	
	public function get_power(){
		$user = $this->get_user('','power');
		return empty($user['power']) ? 0 : $user['power'];
	}
	
}
?>